package com.hhq.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhq.common.enums.ResultEnum;
import com.hhq.common.exception.BusinessException;
import com.hhq.usercenter.domain.model.MenuModel;
import com.hhq.usercenter.domain.model.UserModel;
import com.hhq.usercenter.domain.pojo.MenuInfo;
import com.hhq.usercenter.domain.pojo.UserInfo;
import com.hhq.usercenter.mapper.UserMapper;
import com.hhq.usercenter.security.MenuGrantedAuthority;
import com.hhq.usercenter.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/1/5 15:49
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserModel> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaUpdateWrapper<UserModel> queryWrapper = Wrappers.lambdaUpdate(UserModel.class);
        queryWrapper.eq(UserModel::getUserName, username);
        UserModel userModel = getOne(queryWrapper, false);
        if (null == userModel) {
            throw new BusinessException(ResultEnum.BUSINESS_ERROR.getCode(), "账户或者密码不正确");
        }
        //获取用户的角色，菜单数据
        List<MenuInfo> menuModels = userMapper.queryMenus(userModel.getId());
        Map<Integer, List<MenuInfo>> menuMap = menuModels.stream().collect(Collectors.groupingBy(MenuInfo::getRoleId));
        List<MenuGrantedAuthority> menuGrantedAuthorities = new ArrayList<>();
        menuMap.forEach((k, v) -> menuGrantedAuthorities.add(new MenuGrantedAuthority(String.valueOf(k), v)));
        return new User(userModel.getUserName(), userModel.getPassword(), menuGrantedAuthorities);
    }
}
